#!/usr/bin/env python3

import json
import logging
from typing import Dict, Any, Optional, List, Tuple, Union

logger = logging.getLogger(__name__)

class SalaryAnalyzer:
    def __init__(self, stats_file: str = 'salary_stats.json'):
        """初始化薪资分析器"""
        self.stats_file = stats_file
        self.stats_data: Optional[Dict[str, Any]] = None
        self.load_data()
    
    def load_data(self):
        """加载薪资统计数据"""
        try:
            with open(self.stats_file, 'r', encoding='utf-8') as f:
                self.stats_data = json.load(f)
            logger.info("薪资统计数据加载成功")
        except Exception as e:
            logger.error(f"薪资统计数据加载失败: {e}")
            self.stats_data = {}
    
    def get_ali_salary_range(self, level: str) -> Dict[str, Any]:
        """获取阿里指定职级的薪资范围"""
        result = {
            'level': level,
            'total_comp_mean': None,
            'total_comp_upper_bound': None,
            'total_comp_lower_bound': None,
            'found': False
        }
        
        try:
            # 查找阿里的数据
            if self.stats_data is None:
                logger.error("薪资数据未加载")
                return result
                
            ali_data = self.stats_data.get('技术研发', {}).get('阿里', {})
            level_data = ali_data.get(level, {})
            
            if level_data:
                result.update({
                    'total_comp_mean': level_data.get('total_comp_mean'),
                    'total_comp_upper_bound': level_data.get('total_comp_upper_bound'),
                    'total_comp_lower_bound': level_data.get('total_comp_lower_bound'),
                    'found': True
                })
                logger.info(f"找到阿里{level}职级薪资数据")
            else:
                logger.warning(f"未找到阿里{level}职级的薪资数据")
                
        except Exception as e:
            logger.error(f"获取阿里薪资范围失败: {e}")
        
        return result
    
    def find_equivalent_levels(self, target_salary: float, companies: Optional[List[str]] = None) -> Dict[str, Dict[str, Any]]:
        """根据目标薪资找到其他公司的等效职级"""
        if companies is None:
            companies = ['腾讯', '字节跳动', '百度']
        
        result = {}
        
        try:
            if self.stats_data is None:
                logger.error("薪资数据未加载")
                for company in companies:
                    result[company] = {
                        'level': None,
                        'total_comp_mean': None,
                        'difference': None,
                        'found': False
                    }
                return result
                
            tech_data = self.stats_data.get('技术研发', {})
            
            for company in companies:
                company_data = tech_data.get(company, {})
                if not company_data:
                    logger.warning(f"未找到{company}的薪资数据")
                    result[company] = {
                        'level': None,
                        'total_comp_mean': None,
                        'difference': None,
                        'found': False
                    }
                    continue
                
                # 找到最接近目标薪资的职级
                best_match = self._find_closest_salary_level(company_data, target_salary)
                result[company] = best_match
                
        except Exception as e:
            logger.error(f"查找等效职级失败: {e}")
            for company in companies:
                result[company] = {
                    'level': None,
                    'total_comp_mean': None,
                    'difference': None,
                    'found': False
                }
        
        return result
    
    def _find_closest_salary_level(self, company_data: Dict, target_salary: float) -> Dict[str, Any]:
        """在单个公司数据中找到最接近目标薪资的职级"""
        best_match = {
            'level': None,
            'total_comp_mean': None,
            'difference': float('inf'),
            'found': False
        }
        
        for level, level_data in company_data.items():
            mean_salary = level_data.get('total_comp_mean')
            if mean_salary is not None:
                difference = abs(mean_salary - target_salary)
                if difference < best_match['difference']:
                    best_match.update({
                        'level': level,
                        'total_comp_mean': mean_salary,
                        'difference': difference,
                        'found': True
                    })
        
        return best_match
    
    def analyze_prediction(self, predicted_level: str) -> Dict[str, Any]:
        """分析预测结果，返回薪资范围和等效职级"""
        result = {
            'ali_level': predicted_level,
            'salary_range': {},
            'equivalent_levels': {},
            'analysis_success': False
        }
        
        try:
            # 获取阿里职级的薪资范围
            salary_range = self.get_ali_salary_range(predicted_level)
            result['salary_range'] = salary_range
            
            # 如果找到了阿里的薪资数据，寻找等效职级
            if salary_range['found'] and salary_range['total_comp_mean'] is not None:
                equivalent_levels = self.find_equivalent_levels(salary_range['total_comp_mean'])
                result['equivalent_levels'] = equivalent_levels
                result['analysis_success'] = True
                
                logger.info(f"成功分析{predicted_level}职级: "
                          f"平均薪资{salary_range['total_comp_mean']:.0f}元")
            else:
                logger.warning(f"无法获取{predicted_level}的薪资数据，跳过等效职级匹配")
                
        except Exception as e:
            logger.error(f"薪资分析失败: {e}")
        
        return result
    
    def format_analysis_result(self, analysis_result: Dict[str, Any]) -> Dict[str, Any]:
        """格式化分析结果，用于API响应"""
        formatted = {
            'salary_analysis': {
                'ali_level': analysis_result['ali_level'],
                'salary_range_found': analysis_result['salary_range'].get('found', False)
            },
            'equivalent_levels': {}
        }
        
        salary_range = analysis_result['salary_range']
        if salary_range.get('found'):
            formatted['salary_analysis'].update({
                'total_comp_mean': round(salary_range['total_comp_mean'], 2),
                'total_comp_upper_bound': round(salary_range['total_comp_upper_bound'], 2),
                'total_comp_lower_bound': round(salary_range['total_comp_lower_bound'], 2),
                'salary_range_text': f"{salary_range['total_comp_lower_bound']:.0f} - {salary_range['total_comp_upper_bound']:.0f} 元"
            })
        
        equivalent_levels = analysis_result['equivalent_levels']
        for company, level_info in equivalent_levels.items():
            if level_info.get('found'):
                formatted['equivalent_levels'][company] = {
                    'level': level_info['level'],
                    'total_comp_mean': round(level_info['total_comp_mean'], 2),
                    'salary_difference': round(level_info['difference'], 2)
                }
            else:
                formatted['equivalent_levels'][company] = {
                    'level': None,
                    'total_comp_mean': None,
                    'salary_difference': None,
                    'note': '未找到匹配数据'
                }
        
        return formatted

def test_salary_analyzer():
    """测试"""
    analyzer = SalaryAnalyzer()
    
    # 测试不同职级
    test_levels = ['P4', 'P6', 'P7', 'P8', 'P9']
    
    for level in test_levels:
        print(f"\n=== 测试{level}职级 ===")
        
        # 分析结果
        analysis = analyzer.analyze_prediction(level)
        formatted = analyzer.format_analysis_result(analysis)
        
        print(f"职级: {level}")
        if formatted['salary_analysis']['salary_range_found']:
            print(f"薪资范围: {formatted['salary_analysis']['salary_range_text']}")
            print(f"平均薪资: {formatted['salary_analysis']['total_comp_mean']:.0f}元")
            
            print("\n等效职级:")
            for company, info in formatted['equivalent_levels'].items():
                if info['level']:
                    print(f"  {company}: {info['level']} (平均薪资: {info['total_comp_mean']:.0f}元, "
                          f"差异: {info['salary_difference']:.0f}元)")
                else:
                    print(f"  {company}: 未找到匹配")
        else:
            print("未找到薪资数据")

if __name__ == "__main__":
    test_salary_analyzer()